package org.dynobjects.core;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;

import org.apache.commons.io.IOUtils;
import org.dynobjects.core.xml.Model;
import org.exolab.castor.core.exceptions.CastorException;
import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.mapping.MappingException;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.ValidationException;
import org.xml.sax.InputSource;

public class XmlHandler {

	private byte[] xmlBytes = null;
	private Mapping mapping = null;
	private Object objectToMarshall = null;
	private StringWriter writer = new StringWriter();

	public XmlHandler(Object objetToMarshall,InputStream castorMapping){
		this.objectToMarshall=objetToMarshall;
		setMapping(castorMapping);
	}
	
	public XmlHandler(InputStream modelInputStream, InputStream castorMapping) {
		try {
			this.xmlBytes = IOUtils.toByteArray(modelInputStream);
			setMapping(castorMapping);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	private void setMapping(InputStream castorMapping) {
		mapping = new Mapping();
		mapping.loadMapping(new InputSource(castorMapping));
	}

	public XmlHandler(InputSource inputSource, InputStream castorMapping) {
		this(inputSource.getByteStream(), castorMapping);
	}

	
	public String marshall() throws Exception {
		Marshaller marshaller = new Marshaller();
		
		marshaller.setWriter(writer);
		marshaller.setMapping(mapping);
		marshaller.marshal(objectToMarshall);
		return writer.getBuffer().toString();
	}
	
	public Object unmarshall(Class _class) throws Exception{
		Unmarshaller unmarshaller = new Unmarshaller(_class);
		
		unmarshaller.setMapping(mapping);
		Object obj = unmarshaller.unmarshal(new InputSource(new ByteArrayInputStream(xmlBytes)));
		return  obj;
	}
}
